<template>
  <view class="version-manager">
    <view class="version-list">
      <view 
        v-for="version in sortedVersions" 
        :key="version.id"
        class="version-item"
        :class="{ active: currentVersion?.id === version.id }"
      >
        <view class="version-header" @click="selectVersion(version)">
          <view class="version-badge">
            <text class="badge-text">{{ version.name }}</text>
          </view>
          <view class="version-info">
            <text class="version-time">{{ formatTime(version.timestamp) }}</text>
            <view class="version-change">
              <text class="change-type" :class="getChangeTypeClass(version.changeType)">
                {{ version.changeType }}
              </text>
              <text class="change-desc">{{ version.description }}</text>
            </view>
          </view>
          <view class="version-actions" @click.stop>
            <button 
              class="action-icon-btn"
              @click="toggleDetails(version.id)"
              :title="expandedVersions.includes(version.id) ? '收起' : '展开'"
            >
              {{ expandedVersions.includes(version.id) ? '▲' : '▼' }}
            </button>
            <button 
              class="action-icon-btn"
              @click="startCompare(version)"
              :disabled="!canCompare(version)"
              title="对比"
            >
              ⚖️
            </button>
          </view>
        </view>

        <!-- 展开的详情 -->
        <view class="version-details" v-if="expandedVersions.includes(version.id)">
          <view class="detail-section">
            <text class="detail-label">预报方案:</text>
            <text class="detail-value">{{ version.scheme }}</text>
          </view>
          
          <view class="detail-section" v-if="version.settings">
            <text class="detail-label">配置:</text>
            <text class="detail-value">
              开始时间 {{ formatDateTime(version.settings.startTime) }}, 
              预热期 {{ version.settings.warmupDays }}天, 
              预见期 {{ version.settings.forecastDays }}天
            </text>
          </view>

          <view class="detail-section" v-if="version.rainfallData">
            <text class="detail-label">降雨数据:</text>
            <text class="detail-value">
              {{ version.rainfallData.length }}个时段, 
              总降雨量 {{ getTotalRainfall(version.rainfallData) }}mm
            </text>
          </view>

          <view class="detail-section" v-if="version.result">
            <text class="detail-label">预报结果:</text>
            <text class="detail-value">
              {{ version.result.data?.length || 0 }}个预报点, 
              峰值流量 {{ getPeakFlow(version.result) }} m³/s
            </text>
          </view>

          <view class="detail-actions">
            <button 
              class="detail-btn"
              @click="viewVersion(version)"
            >
              查看详情
            </button>
            <button 
              class="detail-btn detail-btn-danger"
              @click="deleteVersion(version)"
              v-if="versions.length > 1"
            >
              删除版本
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 对比选择提示 -->
    <view class="compare-hint" v-if="compareMode">
      <text class="hint-icon">⚖️</text>
      <view class="hint-content">
        <text class="hint-title">对比模式</text>
        <text class="hint-desc">
          已选择 {{ compareVersion1.name }}，请选择另一个版本进行对比
        </text>
      </view>
      <button class="hint-cancel" @click="cancelCompare">
        取消
      </button>
    </view>
  </view>
</template>

<script>
import { ref, computed } from 'vue'

export default {
  name: 'VersionManager',
  props: {
    versions: {
      type: Array,
      required: true
    },
    currentVersion: {
      type: Object,
      default: null
    }
  },
  emits: ['version-select', 'version-compare', 'version-delete'],
  setup(props, { emit }) {
    const expandedVersions = ref([])
    const compareMode = ref(false)
    const compareVersion1 = ref(null)

    // 按时间倒序排列
    const sortedVersions = computed(() => {
      return [...props.versions].sort((a, b) => 
        new Date(b.timestamp) - new Date(a.timestamp)
      )
    })

    const toggleDetails = (versionId) => {
      const index = expandedVersions.value.indexOf(versionId)
      if (index > -1) {
        expandedVersions.value.splice(index, 1)
      } else {
        expandedVersions.value.push(versionId)
      }
    }

    const selectVersion = (version) => {
      emit('version-select', version)
    }

    const startCompare = (version) => {
      if (compareMode.value) {
        // 第二次选择，开始对比
        emit('version-compare', compareVersion1.value, version)
        compareMode.value = false
        compareVersion1.value = null
      } else {
        // 第一次选择
        compareMode.value = true
        compareVersion1.value = version
      }
    }

    const cancelCompare = () => {
      compareMode.value = false
      compareVersion1.value = null
    }

    const canCompare = (version) => {
      // 必须有结果才能对比
      return version.result && version.result.data && version.result.data.length > 0
    }

    const viewVersion = (version) => {
      selectVersion(version)
      uni.showToast({
        title: '已切换到 ' + version.name,
        icon: 'success'
      })
    }

    const deleteVersion = (version) => {
      uni.showModal({
        title: '确认删除',
        content: `确定要删除版本 ${version.name} 吗？此操作不可恢复。`,
        success: (res) => {
          if (res.confirm) {
            emit('version-delete', version)
          }
        }
      })
    }

    const formatTime = (timestamp) => {
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      // 1分钟内
      if (diff < 60 * 1000) {
        return '刚刚'
      }
      // 1小时内
      if (diff < 60 * 60 * 1000) {
        const minutes = Math.floor(diff / (60 * 1000))
        return `${minutes}分钟前`
      }
      // 24小时内
      if (diff < 24 * 60 * 60 * 1000) {
        const hours = Math.floor(diff / (60 * 60 * 1000))
        return `${hours}小时前`
      }
      // 超过24小时
      return date.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const formatDateTime = (dateTimeStr) => {
      if (!dateTimeStr) return '-'
      const date = new Date(dateTimeStr)
      return date.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const getChangeTypeClass = (changeType) => {
      const typeMap = {
        '方案选择': 'type-scheme',
        '参数修改': 'type-params',
        '配置修改': 'type-settings',
        '降雨修改': 'type-rainfall',
        '执行预报': 'type-execute'
      }
      return typeMap[changeType] || 'type-default'
    }

    const getTotalRainfall = (rainfallData) => {
      if (!rainfallData || rainfallData.length === 0) return 0
      const total = rainfallData.reduce((sum, item) => sum + (item.value || 0), 0)
      return total.toFixed(1)
    }

    const getPeakFlow = (result) => {
      if (!result?.data?.length) return '-'
      const max = Math.max(...result.data.map(item => item.flow))
      return max.toFixed(2)
    }

    return {
      expandedVersions,
      compareMode,
      compareVersion1,
      sortedVersions,
      toggleDetails,
      selectVersion,
      startCompare,
      cancelCompare,
      canCompare,
      viewVersion,
      deleteVersion,
      formatTime,
      formatDateTime,
      getChangeTypeClass,
      getTotalRainfall,
      getPeakFlow
    }
  }
}
</script>

<style scoped>
.version-manager {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.version-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 600px;
  overflow-y: auto;
}

.version-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fff;
  transition: all 0.3s;
}

.version-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.version-item.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.version-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  cursor: pointer;
}

.version-badge {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
  border-radius: 8px;
}

.badge-text {
  font-size: 14px;
  font-weight: 600;
  color: #fff;
}

.version-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.version-time {
  font-size: 12px;
  color: #909399;
}

.version-change {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.change-type {
  padding: 2px 8px;
  font-size: 12px;
  border-radius: 3px;
  font-weight: 500;
}

.type-scheme {
  background-color: #e6f7ff;
  color: #1890ff;
}

.type-params {
  background-color: #f0f9ff;
  color: #409eff;
}

.type-settings {
  background-color: #f6ffed;
  color: #52c41a;
}

.type-rainfall {
  background-color: #fff7e6;
  color: #fa8c16;
}

.type-execute {
  background-color: #fff1f0;
  color: #f5222d;
}

.change-desc {
  font-size: 13px;
  color: #606266;
}

.version-actions {
  display: flex;
  gap: 8px;
}

.action-icon-btn {
  width: 32px;
  height: 32px;
  padding: 0;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-icon-btn:hover:not([disabled]) {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.action-icon-btn[disabled] {
  opacity: 0.4;
  cursor: not-allowed;
}

.version-details {
  padding: 16px;
  border-top: 1px solid #e4e7ed;
  background-color: #fafafa;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-section {
  display: flex;
  gap: 8px;
  font-size: 13px;
}

.detail-label {
  color: #909399;
  font-weight: 500;
  min-width: 80px;
}

.detail-value {
  color: #606266;
  flex: 1;
}

.detail-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.detail-btn {
  padding: 6px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s;
}

.detail-btn:hover {
  border-color: #409eff;
  color: #409eff;
  background-color: #ecf5ff;
}

.detail-btn-danger {
  color: #f56c6c;
  border-color: #f56c6c;
}

.detail-btn-danger:hover {
  background-color: #fef0f0;
}

.compare-hint {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: linear-gradient(135deg, #fff7e6 0%, #fffbe6 100%);
  border-left: 3px solid #ffa940;
  border-radius: 6px;
}

.hint-icon {
  font-size: 24px;
}

.hint-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.hint-title {
  font-size: 14px;
  font-weight: 600;
  color: #d46b08;
}

.hint-desc {
  font-size: 13px;
  color: #ad6800;
}

.hint-cancel {
  padding: 6px 16px;
  border: 1px solid #d46b08;
  border-radius: 4px;
  background-color: #fff;
  color: #d46b08;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s;
}

.hint-cancel:hover {
  background-color: #fff7e6;
}

/* 滚动条样式 */
.version-list::-webkit-scrollbar {
  width: 6px;
}

.version-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.version-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.version-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>

